from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
from itsdangerous import BadData

from . import constants

def generate_save_user_token(openid):
    #将openid的明文　转化为密文
    # 创建序列化器的对象
    serializer = TJWSSerializer(settings.SECRET_KEY,constants.SAVE_QQ_USER_TOKEN_EXPRISE)
    #构造远的数据
    data = {'openid':openid}
    #序列化字典　dumps返回ｂｙｔｅｓ类型的数据
    token = serializer.dumps(data).decode()

    return token


def check_save_user_token(access_token):
    """
    将密文openid转成明文openid
    :param access_token: 密文openid
    :return: 明文openid
    """
    # 创建序列化器对象
    s = TJWSSerializer(settings.SECRET_KEY, constants.SAVE_QQ_USER_TOKEN_EXPRISE)
    # 解码密文openid
    try:
        data = s.loads(access_token)
        openid = data.get('openid')
    except BadData:
        return None
    else:
        return openid
